<template>
  <div class="snow-page">
    <a-card title="网关添加" style="width: 99%" hoverable>
      <template #extra>
        <a-button size="mini" type="primary" @click="goBack">返回</a-button>
      </template>
      <div class="">
        <div class="snow-inner-page">
          <a-row :gutter="16">
            <a-form ref="formRef" :size="form.size" :model="form" auto-label-width @submit="handleSubmit">
              <div style="display: flex">
                <a-col :span="4"></a-col>
                <a-col :span="12">
                  <a-form-item field="scene_id" label="企业" :rules="[{ required: true, message: '企业不能为空' }]"
                    :validate-trigger="['change', 'input']">
                    <a-tree-select v-model="form.scene_id" :field-names="filrname" :data="treeNodes" placeholder="企业"
                      allow-clear allow-search @change="changeTree"></a-tree-select>
                  </a-form-item>
                  <a-form-item field="cq_equip_code" label="网关编码">
                    <a-input v-model="form.cq_equip_code" placeholder="自动生成" allow-clear disabled />
                  </a-form-item>
                  <a-form-item field="device_code" label="网关号" :rules="[{ required: true, message: '网关号不能为空' }]">
                    <a-input v-model="form.device_code" placeholder="网关号" allow-clear />
                  </a-form-item>

                  <a-form-item field="name" label="网关名称" :rules="[{ required: true, message: '网关名称不能为空' }]">
                    <a-input v-model="form.name" placeholder="请输入网关名称" allow-clear />
                  </a-form-item>

                  <a-form-item field="iot_node_type" label="通信协议" :rules="[{ required: true, message: '通信协议不能为空' }]">
                    <a-select v-model="form.iot_node_type" placeholder="通信协议" allow-clear @change="changeType">
                      <a-option v-for="(item, index) in options81" :key="index" :value="item.id">{{ item.name
                        }}</a-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item field="iot_protocal_category" label="数据协议"
                    :rules="[{ required: true, message: '数据协议不能为空' }]">
                    <a-select v-model="form.iot_protocal_category" placeholder="数据协议" allow-clear>
                      <a-option v-for="(item, index) in options300" :key="index" :value="item.dictionary_name">{{
                        item.name
                      }}</a-option>
                    </a-select>
                  </a-form-item>

                  <a-form-item field="lonLat" label="网关经纬度">
                    <a-input-search v-model="form.lonLat" placeholder="请输入网关经纬度" allow-clear disabled
                      enter-button="选择地址" @search="onSearch">
                    </a-input-search>
                  </a-form-item>

                  <a-form-item field="cq_hazard_code" label="危险源编码">
                    <a-select v-model="form.cq_hazard_code" placeholder="危险源编码" allow-clear allow-search>
                      <a-option v-for="(item, index) in weixianLi" :key="index" :value="item.hazard_code">{{
                        item.hazard_name
                      }}</a-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item field="cq_equip_type" label="网关类型" :rules="[{ required: true, message: '网关类型不能为空' }]">
                    <a-input v-model="form.cq_equip_type" placeholder="请输入网关类型" allow-clear>
                   </a-input>
                  </a-form-item>
                  <!-- <a-form-item field="cq_equip_type" label="网关类型" :rules="[{ required: true, message: '网关类型不能为空' }]">
                    <a-select v-model="form.cq_equip_type" placeholder="请输入网关类型" allow-clear allow-search>
                      <a-option v-for="(item, index) in options558" :key="index" :value="item.dictionary_name">{{
                        item.name
                      }}</a-option>
                    </a-select>
                  </a-form-item> -->

                  <!-- <a-form-item field="cq_equip_medium" label="网关介质" :rules="[{ required: true, message: '网关介质不能为空' }]">
                    <a-input v-model="form.cq_equip_medium" placeholder="网关介质" allow-clear />
                  </a-form-item> -->

                  <a-form-item field="frequency" label="采集频率" :rules="[{ required: true, message: '采集频率不能为空' }]">
                    <a-input-number v-model="form.frequency" placeholder="采集频率(单位s)" allow-clear />
                  </a-form-item>
                  <a-form-item field="seq" label="排序" :rules="[{ required: true, message: '排序不能为空' }]">
                    <a-input-number v-model="form.seq" placeholder="排序" allow-clear />
                  </a-form-item>
                  <a-form-item field="infos" label="网关描述">
                    <a-textarea v-model="form.infos" placeholder="网关描述" allow-clear />
                  </a-form-item>
                </a-col>

                <!-- <a-col :span="12"> -->
                  <!-- <a-form-item field="cq_location_code" label="仓间位置及编号">
                    <a-input v-model="form.cq_location_code" placeholder="仓间位置及编号" allow-clear />
                  </a-form-item>
                  <a-form-item field="cq_fire_evaluate" label="仓间火灾危险性评价">
                    <a-input v-model="form.cq_fire_evaluate" placeholder="仓间火灾危险性评价" allow-clear> </a-input>
                  </a-form-item>
                  <a-form-item field="cq_max_storage" label="仓间最大储存量">
                    <a-input v-model="form.cq_max_storage" placeholder="仓间最大储存量" allow-clear />
                  </a-form-item>
                  <a-form-item field="cq_goods_type" label="仓间储存物品类别">
                    <a-input v-model="form.cq_goods_type" placeholder="仓间储存物品类别" allow-clear />
                  </a-form-item>
                  <a-form-item field="cq_goods_name_num" label="实时储存物品的名称、数量">
                    <a-input v-model="form.cq_goods_name_num" placeholder="实时储存物品的名称、数量" allow-clear />
                  </a-form-item>
                  <a-form-item field="cq_goods_local" label="储存物品堆放位置">
                    <a-input v-model="form.cq_goods_local" placeholder="储存物品堆放位置" allow-clear />
                  </a-form-item>
                  <a-form-item field="cq_storage" label="库存量">
                    <a-input-number v-model="form.cq_storage" placeholder="库存量" allow-clear :min="0" />
                  </a-form-item>
                  <a-form-item field="cq_turnover" label="周转量">
                    <a-input-number v-model="form.cq_turnover" placeholder="周转量" allow-clear :min="0" />
                  </a-form-item>
                  <a-form-item field="cq_emergency_plan" label="仓间应急预案">
                    <a-input v-model="form.cq_emergency_plan" placeholder="仓间应急预案" allow-clear />
                  </a-form-item> -->
                 
                  <!-- /infos -->
                <!-- </a-col> -->
              </div>
              <div style="text-align: center; margin-left: 35%">
                <a-form-item>
                  <a-space>
                    <a-button type="primary" html-type="submit">提交</a-button>
                    <a-button @click="onReset">重置</a-button>
                  </a-space>
                </a-form-item>
              </div>
            </a-form>
          </a-row>
        </div>
      </div>

      <a-modal v-model:visible="mapopen" title="选择位置" width="50%">
        <div id="mapContainer" style="width: 100%; height: 400px"></div>
        <div class="input-container">
          <input v-model="longitude" @keyup.enter="locatePosition" placeholder="输入经度" class="coordinate-input" />
          <input v-model="latitude" @keyup.enter="locatePosition" placeholder="输入纬度" class="coordinate-input" />
          <button @click="locatePosition" class="locate-button">定位</button>
        </div>
      </a-modal>
    </a-card>
  </div>
</template>


<script setup lang="ts">
import { Message } from "@arco-design/web-vue";
import { ref, reactive, onMounted } from "vue";
// import {regionData} from "element-china-area-data";
import { getAllqiyeAPI } from "@/api/modules/qiye/index";
import { addprojectAPI, updateprojectAPI } from "@/api/modules/project/index";
import { getDictBycodeAPI, getDictBycode2API } from "@/api/modules/dictionary/index";
import { getweAPI2 } from "@/api/modules/weixian/index";
// import axios from "axios";
const router = useRouter();
onMounted(() => {
  getDictBycodeAPIfun();
  getDictBycodeAPIfun2();

  getInit();
  getFuzhi();
});

function changeTree(value) {
  for (let i = 0; i < treeAllNodes.value.length; i++) {
    if (value == treeAllNodes.value[i].id) {
      getDictBycodeAPIfun3(treeAllNodes.value[i].cq_company_code);
      return
    }
  }
}

const weixianLi = ref([]);
async function getDictBycodeAPIfun3(code) {
  let obj = {
    paged: 1,
    pageSize: 500
  }
  let obj2 = {
    hazard_name: "",
    company_code: code
  }
  weixianLi.value = []
  let res = await getweAPI2(obj, obj2);
  if (res.status == 2) {
    weixianLi.value = res.data.data;
    let userInfo = JSON.parse(localStorage.getItem("user-info") as string);
    if (userInfo.sharedObject.id) {
      form.cq_hazard_code = userInfo.sharedObject.cq_hazard_code;
    }

  }
}

const options81 = ref([]);
async function getDictBycodeAPIfun() {
  // let obj={}
  let res = await getDictBycodeAPI(81);
  if (res.status == 2) {
    options81.value = res.data;
  }
}
const options558 = ref([]);
async function getDictBycodeAPIfun2() {
  let res = await getDictBycodeAPI(558);
  if (res.status == 2) {
    options558.value = res.data;
  }
}
const options300 = ref([]);

async function changeType(val) {
  if (val == 83) {
    let res = await getDictBycodeAPI(300);
    if (res.status == 2) {
      options300.value = res.data;
    }
  } else if (val == 84) {
    let res = await getDictBycode2API(305);
    if (res.status == 2) {
      options300.value = res.data;
    }
  }
}

function getFuzhi() {
  let userInfo = JSON.parse(localStorage.getItem("user-info") as string);
  if (userInfo.sharedObject.id) {

    form.scene_id = userInfo.sharedObject.scene_id;


    setTimeout(function () {
      for (let i = 0; i < treeAllNodes.value.length; i++) {
        if (form.scene_id == treeAllNodes.value[i].id) {
          getDictBycodeAPIfun3(treeAllNodes.value[i].cq_company_code);
          return
        }
      }
    }, 300)
    form.name = userInfo.sharedObject.name;
    form.device_code = userInfo.sharedObject.device_code;
    form.cq_equip_code = userInfo.sharedObject.cq_equip_code;

    form.lonLat = userInfo.sharedObject.lonLat;
    form.cq_equip_type = (userInfo.sharedObject.cq_equip_type);
    form.cq_equip_medium = userInfo.sharedObject.cq_equip_medium;
    form.cq_equip_status = userInfo.sharedObject.cq_equip_status ? userInfo.sharedObject.cq_equip_status : undefined;
    form.cq_location_code = userInfo.sharedObject.cq_location_code;
    form.cq_fire_evaluate = userInfo.sharedObject.cq_fire_evaluate;
    form.cq_max_storage = userInfo.sharedObject.cq_max_storage;
    form.cq_goods_type = userInfo.sharedObject.cq_goods_type;
    form.cq_goods_name_num = userInfo.sharedObject.cq_goods_name_num;
    form.cq_goods_local = userInfo.sharedObject.cq_goods_local;
    form.cq_storage = userInfo.sharedObject.cq_storage;
    form.cq_turnover = userInfo.sharedObject.cq_turnover;
    form.cq_emergency_plan = userInfo.sharedObject.cq_emergency_plan;
    form.infos = userInfo.sharedObject.infos;
    form.id = userInfo.sharedObject.id;
    form.iot_node_type = userInfo.sharedObject.iot_node_type;
    changeType(form.iot_node_type);
    form.iot_protocal_category = userInfo.sharedObject.iot_protocal_category;
    form.seq = userInfo.sharedObject.seq;
    form.frequency = userInfo.sharedObject.frequency;
  }

}

const mapopen = ref(false);

const treeNodes = ref([]);
const treeAllNodes = ref([]);
async function getInit() {
  let obj = {};
  let res = await getAllqiyeAPI(obj);
  if (res.status == 2) {
    treeNodes.value = generateTreeNodes(res.data);
    treeAllNodes.value = res.data
  }
}

const filrname = ref({
  key: "id",
  value: "id",
  title: "name",
  children: "children"
});

function generateTreeNodes(data) {
  const nodeMap = new Map();
  const rootNodes = [];

  // First pass: create nodes and store them in a map
  data.forEach(item => {
    const node = {
      id: item.id,
      name: item.name,
      children: [],
      data: item // Store all original data
    };
    nodeMap.set(item.cq_company_code, node);
  });

  // Second pass: build the tree structure
  data.forEach(item => {
    const node = nodeMap.get(item.cq_company_code);
    if (item.cq_parent_code === "0") {
      rootNodes.push(node);
    } else {
      const parentNode = nodeMap.get(item.cq_parent_code);
      if (parentNode) {
        parentNode.children.push(node);
      } else {
        console.warn(`Parent node ${item.cq_parent_code} not found for ${item.cq_company_code}`);
        rootNodes.push(node); // Add to root if parent not found
      }
    }
  });

  return rootNodes;
}

const handleSubmit = async ({ values, errors }) => {
  if (errors) {
    return;
  }
  let res: any = "";
  if (form.id) {
    res = (await updateprojectAPI(values)) as any;
  } else {
    res = (await addprojectAPI(values)) as any;
  }

  if (res.status == 2) {
    Message.success("操作成功");
    // router.back();
  } else {
    Message.error(res.statusMsg);
  }
};

// 将序列化的字符串美观输出，\t 换行

const form = reactive({}) as any;

const formRef = ref();
const onReset = () => {
  formRef.value.resetFields();
};

function goBack() {
  router.back();
}

function onSearch() {
  mapopen.value = true;

  setTimeout(function () {
    initMap();
  }, 500);
}
const longitude = ref("");
const latitude = ref("");
const map = ref({}) as any;
let marker: any;
const locatePosition = () => {
  const lon = parseFloat(longitude.value);
  const lat = parseFloat(latitude.value);

  form.lonLat = lon + "," + lat;
  if (isNaN(lon) || isNaN(lat)) {
    alert("请输入有效的经纬度");
    return;
  }

  const lnglat = new window.T.LngLat(lon, lat);

  // 移动地图中心
  map.value.panTo(lnglat);

  // 清除现有标记
  map.value.clearOverLays();

  // 添加新标记
  marker = new window.T.Marker(lnglat);
  map.value.addOverLay(marker);

  // 设置缩放级别
  map.value.setZoom(13);
};
function initMap() {
  //map创建地图实例

  map.value = new T.Map(document.getElementById("mapContainer"));

  // 设置地图中心点和缩放级别
  map.value.centerAndZoom(new T.LngLat(121.42638, 31.63153), 11);

  map.value.on("click", function (e) {
    map.value.clearOverLays();
    longitude.value = e.lnglat.lng;
    latitude.value = e.lnglat.lat;
    form.lonLat = e.lnglat.lng + "," + e.lnglat.lat;

    // getAddressInfo();
    const position = new T.LngLat(e.lnglat.lng, e.lnglat.lat);
    let icon = new T.Icon({
      iconUrl: "./icon.png", // 请求图标图片的URL
      iconSize: new T.Point(40, 40), // 图标可视区域的大小
      iconAnchor: new T.Point(30, 30) // 图标的定位锚点
    });
    const marker = new T.Marker(position, { icon: icon });
    map.value.addOverLay(marker);
  });
}

// async function getAddressInfo() {
//   let Tokens = "20f5dad7c9e6207216d4d7d971fbed3f";
//   let postStr = {
//     lon: form.lon,
//     lat: form.lat,
//     ver: 1
//   };
//   let url = "https://api.tianditu.gov.cn/geocoder";
//   // Lambda写法
//   let res = await axios({
//     method: "get",
//     url: url,
//     params: {
//       postStr: JSON.stringify(postStr),
//       type: "geocode",
//       tk: Tokens
//     },
//     timeout: 1000
//   });
//   // 响应成功回调
//   if (res.data.msg == "ok") {
//     form.cq_address_worksite = res.data.result.formatted_address;
//   }
// }
</script>

<style lang="scss">
.arco-input-wrapper .arco-input[disabled] {
  -webkit-text-fill-color: #8f7e7e !important;
}

.arco-form-item {
  margin-bottom: 10px !important;
}

.arco-input-wrapper.arco-input-disabled .arco-input-prefix,
.arco-input-wrapper.arco-input-disabled .arco-input-suffix {
  color: #000 !important;
}

.input-container {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 1000;
  display: flex;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 10px;
  border-radius: 4px;
}

.coordinate-input {
  padding: 8px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 4px;
  width: 120px;
  margin-right: 5px;
}

.locate-button {
  padding: 8px 16px;
  font-size: 14px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.locate-button:hover {
  background-color: #45a049;
}
</style>
